package com.bank.controller;

import com.bank.constant.MessageConstant;
import com.bank.dto.AccountOperationDTO;
import com.bank.dto.TransactionPageQueryDTO;
import com.bank.result.PageResult;
import com.bank.result.Result;
import com.bank.service.AccountService;
import com.bank.service.BillService;
import com.bank.service.BillTransactionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;

@CrossOrigin
@RestController
@RequestMapping("/bill")
@Slf4j
@Api(tags = "3.存款管理")
public class BillController {
    @Autowired
    private AccountService accountService;
    @Autowired
    private BillService billService;
    @Autowired
    private BillTransactionService billTransactionService;

    @PostMapping("/changeBalance")
    @ApiOperation("存取款，转账操作")
    @Transactional
    public Result<String> changeBalance(@RequestBody @Valid AccountOperationDTO operationDTO) {
        log.info("存取款：{}", operationDTO);
        billService.changeBalance(operationDTO);

        String msg = operationDTO.getAmount().compareTo(BigDecimal.ZERO) > 0
                ? MessageConstant.DEPOSIT_SUCCESS
                : (operationDTO.getRelatedAccount() == null
                ? MessageConstant.WITHDRAW_SUCCESS
                : MessageConstant.TRANSFER_SUCCESS);

        return Result.success(msg);
    }

    @GetMapping("/getBalance")
    @ApiOperation("根据账户id查询余额")
    public Result<BigDecimal> getBalanceByAccountId(Long accountId) {
        BigDecimal balanceByAccountId = billService.getBalanceByAccountId(accountId);
        log.info("查询账户余额成功:{}", balanceByAccountId);
        return Result.success(balanceByAccountId, MessageConstant.ACCOUNT_BALANCE_QUERY_SUCCESS);
    }

    @GetMapping("/getTransactions")
    @ApiOperation("根据账户id查询交易记录")
    public Result<PageResult> getTransactionsByAccountId(TransactionPageQueryDTO queryDTO) {
        log.info("查询交易记录：{}", queryDTO);
        PageResult pageResult = billTransactionService.pageQuery(queryDTO);
        return Result.success(pageResult, MessageConstant.TRANSACTION_QUERY_SUCCESS);
    }
}
